package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired(required = false)
    private SpuMapper spuMapper;

    @Autowired     //注入分布式id
    private IdWorker idWorker;

    @Autowired(required = false)
   private CategoryMapper categoryMapper;

    @Autowired(required = false)
   private BrandMapper brandMapper;

    @Autowired(required = false)
    private SkuMapper skuMapper;

    @Autowired(required = false)
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * 查询全部列表
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     *
     * @param goodsDto
     */
    @Override
    @Transactional//开启事务
    public void add(GoodsDto goodsDto) {
        //1.添加spu
        Spu spu = goodsDto.getSpu();
        //为商品设置分布式id
        long spuId = idWorker.nextId();
        spu.setId(String.valueOf(spuId));
        //设置状态:是否为删除状态,是否上架状态,是否审核状态
        spu.setIsDelete("0");
        // 商品上架状态
        spu.setIsMarketable("0");
        //审核状态   0 未审核状态
        spu.setStatus("0");
        spuMapper.insertSelective(spu);

        //绑定品牌与分类的关系

        //2.添加sku
        this.saveSkuList(goodsDto);
    }

    /**
     * 添加sku信息
     *
     * @param goodsDto
     */
    private void saveSkuList(GoodsDto goodsDto) {
        Spu spu = goodsDto.getSpu();

        //查询分类对象
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        //查询品牌的对象
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());




        //设置品牌与分类的关联关系
        //查询关联表

        CategoryBrand categoryBrand = new CategoryBrand();

        categoryBrand.setBrandId(spu.getBrandId());

        categoryBrand.setCategoryId(spu.getCategory3Id());

        int count = categoryBrandMapper.selectCount(categoryBrand);

        if (count == 0){
            //代表品牌与分类还没有关联关系
            categoryBrandMapper.insert(categoryBrand);

        }


        //获取sku列表信息
        List<Sku> skuList = goodsDto.getSkuList();
        //非空判断
        if (skuList != null) {
            //不为空九田家数据
            //遍历skulist循环填充数据并保存到数据库
            for (Sku sku : skuList) {
                //设置sku的id
                sku.setId(String.valueOf(idWorker.nextId()));
                //设置sku的规格
                if (StringUtils.isEmpty(sku.getSpec())) {
                    //如果为空,给默认值
                    sku.setSpec("{}");
                }
                //设置sku的名称:spu名称+sku规格
                String skuName = spu.getName();
                //sku规格是一个json字符串,转换为map集合
                Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                if (specMap != null && specMap.size() > 0) {
                    //代表有内容的
                    for (String value : specMap.values()) {
                        skuName +=" "+ value;
                    }
                }
                sku.setName(skuName);
                //2020年2月18日14:29:54

                //设置spuid
                sku.setSpuId(spu.getId());

                //设置创建与修改时间
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());

                //设置商品分类id
                sku.setCategoryId(category.getId());

                //设置商品分类名称
                sku.setCategoryName(category.getName());

                //设置品牌名称
                sku.setBrandName(brand.getName());

                //当前的sku添加到数据库
                skuMapper.insertSelective(sku);


            }


        }

    }


    /**
     * 修改商品
     *
     * @param goodsDto
     */
    @Override
    @Transactional
    public void update(GoodsDto goodsDto) {
        //修改spu
        Spu spu = goodsDto.getSpu();

        spuMapper.updateByPrimaryKey(spu);

        //修改sku
        Example example = new Example(Sku.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("spuId",spu.getId());
        //删除原有的sku列表
        skuMapper.deleteByExample(example);

        //现有的新的sku列表进行重新添加
        this.saveSkuList(goodsDto);

    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    @Transactional
    public void delete(String id) {
        //逻辑删除

        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //判断当前商品是否处于下架状态
        if (spu ==null){

            throw new RuntimeException("当前商品不存在");

        }

        if (!spu.getIsMarketable().equals("0")){
            throw new RuntimeException("当前商品必须为下架状态才能删除");
        }

        //如果是下架状态则修改对应的标记为逻辑删除
        spu.setIsDelete("1");

        //重置审核状态为0
        spu.setStatus("0");

        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 条件查询
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Spu>) spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Spu>) spuMapper.selectByExample(example);
    }

    /**
     *  根据id 查询spu与sku列表 信息
     * @param id
     * @return
     */
    @Override
    public GoodsDto findGoodsDtoById(String id) {
        GoodsDto goodsDto  = new GoodsDto();

        //  spu  sku

        //查询spu 信息，封装到goodsDto 中
        Spu spu = spuMapper.selectByPrimaryKey(id);

        goodsDto.setSpu(spu);

        // 查询sku 集合，封装到goodsDto中
        Example example = new Example(Sku.class);

        Example.Criteria criteria = example.createCriteria();

        //根据spu进行sku列表查询
        criteria.andEqualTo("spuId",id);

        List<Sku> skuList = skuMapper.selectByExample(example);

        goodsDto.setSkuList(skuList);

        return goodsDto;
    }


    /**
     *   审核商品并自动上架
     * @param id
     */
    @Override
    @Transactional
    public void audit(String id) {
        // 查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if (spu == null){
            throw new RuntimeException("当前商品不存在");
        }
        //查询当前spu是否处于删除状态 ，
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("当前商品处于删除状态");
        }


        //不处于删除状态，修改审核状态为1 ，上下架状态为1
        spu.setStatus("1");
        spu.setIsMarketable("1");

        //执行修改操作

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品下架
     * @param id
     */
    @Override

    @Transactional
    public void pull(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        if (spu == null){
            throw new RuntimeException("当前商品不存在");
        }
        //当前商品是否是处于删除状态
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("当前商品处于删除状态");
        }


        //商品处于未删除状态的话，则修改上下架状态为已下架  0

        spu.setIsMarketable("0");


        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     *    商品的上架功能
     * @param id
     */
    @Override
    @Transactional
    public void put(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //判断商品是否纯在

        if (spu == null){
            throw new RuntimeException("当前商品不存在");
        }
        //商品状态必须是已经审核过得状态(1)
        if (!spu.getStatus().equals("1")){

            throw new RuntimeException("当前状态未审核");

        }

        //修改审核状态
        spu.setIsMarketable("1");

        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     *    逻辑删除 还原商品
     * @param id
     */
    @Override
    @Transactional
    public void restore(String id) {
        //spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //当前商品处于已删除状态
        if (!"1".equals(spu.getIsDelete())){
            throw new RuntimeException("此商品未处于删除状态");
        }

        //修改相关的属性字段保存操作
        spu.setIsDelete("0");
        //给个审核状态 为未审核
        spu.setStatus("0");

        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     *      物理删除商品
     * @param id
     */
    @Override
    public void relDel(String id) {

        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //判断当前商品是否处于已删除状态
        if (!"1".equals(spu.getIsDelete())){

            //处于未删除状态
            throw new RuntimeException("此商品未处于删除状态");

        }

        spuMapper.deleteByPrimaryKey(id);

    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andEqualTo("sn", searchMap.get("sn"));
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andEqualTo("isMarketable", searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
